﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

namespace ScrumProject.Models
{
    public class CommentRepository : IDisposable
    {
        SMRPO6Context db = new SMRPO6Context();

        public void AddCommentToPost(Comment comment)
        {
            using (var db = new SMRPO6Context())
            {
                db.Database.ExecuteSqlCommand("exec dbo.AddComment  @Content, @Time, @PostId, @UserId",
                                              new SqlParameter("Content", comment.Content),
                                              new SqlParameter("Time", comment.Time),
                                              new SqlParameter("PostId", comment.PostId),
                                              new SqlParameter("UserId", comment.UserId));

                db.SaveChanges();

            }

        }



        

        public IQueryable<Comment> GetCommentsByUser(int id)
        {
            return from Comment in db.Comments
                   join User in db.Users on Comment.UserId equals User.Id
                   where Comment.UserId == id
                   select Comment;
        }

       
        public Comment getComment(int id)
        {
            return (from Comment in db.Comments
                    where Comment.Id == id
                    select Comment).SingleOrDefault();
        }


       
        public void DeleteComment(Comment comment)
        {

            using (var db = new SMRPO6Context())
            {
                db.Comments.Remove(comment);
                db.SaveChanges();
            }

        }
        public IQueryable<Comment> GetPostsComments(int id)
        {
            return from Comment in db.Comments
                   where Comment.PostId == id
                   select Comment;
        }
        public void DeleteAllCommentsForPost(int postId) {
            foreach (Comment comment in GetPostsComments(postId))
            {
                DeleteComment(comment);
            
            }
            Save();
        }
  

        public void Save()
        {
            db.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    db.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}